package beans;

import java.util.HashSet;
import java.util.Set;

import javax.ejb.EJB;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;
import javax.faces.context.FacesContext;

import utils.Navigation;
import dto.MemberDTO;
import dto.VoteDTO;
import entitymanagers.VoteManager;

@ManagedBean(name = "voteBean")
@ViewScoped
public class VoteBean {
	
	@EJB
	private VoteManager voteMngr;
	
	private VoteDTO vote;
	private String partyID;
	
	private Set<String> memberIDs;

	public VoteDTO getVote() {
		if (vote == null){
			vote = new VoteDTO();
		}
		return vote;
	}

	public void setVote(VoteDTO vote) {
		this.vote = vote;
	}
	
	public String confirmVote() {
		if (isVoteFull()){
			return null;
		}
		getVote().setMemberElectionVotes(new MemberDTO[getMemberIDs().size()]);
		int i = 0;
		for (String memberID : getMemberIDs()){
			vote.getMemberElectionVotes()[i++].setIdMember(memberID);
		}
		vote.getParty().setPartyID(getPartyID());
		voteMngr.addVote(vote);
		return Navigation.HOME;
		
		
	}
	
	public void addMember(){
		String memberID = FacesContext.getCurrentInstance().getExternalContext().getRequestParameterMap().get("memberID");
		if (memberID != null && memberID != ""){
			if (!isVoteFull()){
				getMemberIDs().add(memberID);
			}
		}
	}
	
	public boolean memberInVote(String memberID){
		return getMemberIDs().contains(memberID);
	}
	
	public void deleteMemberFromVote(){
		String memberID = FacesContext.getCurrentInstance().getExternalContext().getRequestParameterMap().get("memberID");
		if (memberID != null && memberID != ""){
			getMemberIDs().remove(memberID);
		}
		
	}
	
	public boolean isVoteFull(){
		return getMemberIDs().size() < 4 && getPartyID() != "" && getPartyID() != null;
	}
	
	private String getPartyID(){
		if (partyID == null){
			partyID = FacesContext.getCurrentInstance().getExternalContext().getRequestParameterMap().get("partyID");
			}
		return partyID;
	}
	
	private Set<String> getMemberIDs(){
		if (memberIDs == null){
			memberIDs = new HashSet<String>();
		}
		return memberIDs;
	}
	
			

}
